<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ICamera</title>
  </head>
  <body>
    <video id="video" autoplay="autoplay"></video>
  </body>
  <script>
    // 获得video摄像头区域
    var video = document.getElementById("video");
    var videoStream = null;
    var stop = true;
    // 页面加载完成自动执行
    window.onload = () => {
      // 获取摄像头视频
      this.getMedia();
    };
    // 双击停止视频并且关闭摄像头
    video.ondblclick = () => {
      // 发送关闭摄像头通知-让主线程发送系统通知
      window.dialogAPI.quitVedio("退出直播");
      this.stopMedia();
      window.opener.postMessage("close-vedio-window");
    };
    // 右键是暂停和开始摄像
    video.oncontextmenu = () => {
      if (stop) {
        window.dialogAPI.resumeVedio("继续直播");
        this.reStartMedia();
      } else {
        window.dialogAPI.pauseVedio("暂停直播");
        this.fakeStopMedia();
      }
    };
    // 重新播放
    function reStartMedia() {
      video.play();
      this.stop = false;
    }
    // 假暂停-后台继续还有视频流
    function fakeStopMedia() {
      video.pause();
      this.stop = true;
    }
    // 结束获取视频流数据
    function stopMedia() {
      this.videoStream.getTracks()[0].stop();
      this.videoStream.getTracks()[1].stop();
    }
    // 获得视频流数据
    function getMedia() {
      var constraints = {
        video: { width: 160, height: 160 },
        audio: true,
      };
      //   H5新媒体接口 navigator.mediaDevices.getUserMedia()
      var promise = navigator.mediaDevices.getUserMedia(constraints);
      promise
        .then(function (MediaStream) {
          video.srcObject = MediaStream;
          video.play();
          this.videoStream = MediaStream;
          this.stop = false;
        })
        .catch(function (PermissionDeniedError) {
          console.log(PermissionDeniedError);
        });
    }
  </script>
</html>

<style>
  #video {
    /* 自适应大小 */
    height: 100%;
    width: 100%;
    display: block;
    /* 设置圆形 */
    border-radius: 50%;
    /* 镜像反转 */
    transform: rotateY(180deg);
    /* 可拖拽 */
    -webkit-app-region: drag;
  }
</style>
